package com.yj.consumer.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@Slf4j
public class DiscoveryController {
    @Autowired
    private DiscoveryClient discoveryClient;
    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @GetMapping("/discovery/{serviceId}")
    public Object discovery(@PathVariable("serviceId") String serviceId) {
        List<String> services = discoveryClient.getServices();//获取注册中心所有服务
        for (String service : services)
            log.info("已注册到Nacos中的服务有：{}", service);
        if (!services.contains(serviceId))
            return "无指定服务" + serviceId;
        List<ServiceInstance> instances = discoveryClient.getInstances(serviceId);//获取指定服务的所有实例
        for (ServiceInstance i : instances)
            log.info("{}服务实例有：{}\t{}\t{}\t{}",
                    i.getServiceId(), i.getInstanceId(), i.getHost(), i.getPort(), i.getUri());
        return instances;
    }

    @GetMapping("/loadBalancer/{serviceId}")
    public Object loadBalancer(@PathVariable("serviceId") String serviceId) {
        ServiceInstance i = loadBalancerClient.choose(serviceId);//根据负载均衡策略获取指定服务的某个实例
        log.info("根据负载均衡策略获取{}服务的实例为：{}\t{}\t{}\t{}",
                i.getServiceId(), i.getInstanceId(), i.getHost(), i.getPort(), i.getUri());
        return i;
    }
}
